/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","fu/app/comm/comm",
    "scprit/followup/app/datatable/datatable.servers.js",
    "scprit/followup/app/datatable/datatable.ui.js","scprit/followup/app/courseReservation/addCourse.ui.js","scprit/followup/app/courseReservation/upload.js"],function($,$bb,$comm,$datatableServers,$datatableUi,$addCourseUi,$upload){
    var servers = {};
    var URL = $bb.baseUrl("followup");
    /**
     * 入参
     */
    var inParams = function(args){
        var data = JSON.stringify({
            data: {
                "args": JSON.stringify(args),
                "flag": 1,
                "courseDate":$.trim($('#serchCourseDate').val()),
                "lecturerName": $.trim($('#serchLecturerName').val()),
                "courseName": $.trim($('#serchCourseName').val()),
                "startDate": $.trim($('#serchStartDate').val()),
                "endDate": $.trim($('#serchEndDate').val()),
            }
        });
        return data;
    }
    /**
     * 出参
     */
    var outParams = function(data){
        return data.rows;
    }
    /**
     * columns
     */
    var columnsHisNo = function(e){
        return e.hisNo?e.hisNo:e.hisNo1 ? e.hisNo1 : e.hisNo2 ? e.hisNo2 : e.hisNo3 ? e.hisNo3 : "-";
    }
    var columnsPatientName = function(e){
        var h = e.imgAddress?('<img class="pic-sex" src='+e.imgAddress+'>'):"";
        return h;
    }
    var columnsData = function(){
        var columnsArr = ["id",columnsPatientName,"courseName",'lecturerName','courseDate','upperLimit',"startTime","endTime",null];
        return $datatableServers.getColumnsData(columnsArr);
    }
    /**
     * 行绘制回调函数
     */
    var rowCallback = function(row, data, index) {
        var h = '<div class="btn-look btn-detail">查看</div><div class="btn-update btn-look">修改</div><div class="btn-delete btn-look">删除</div>';
        $('td:last()', row).html(h).css("width","120px");
        $("td:last() .btn-look",row).unbind("click");
        $("td:last() .btn-update,td:last() .btn-detail",row).click(function(){
        	var isUpdate = !$(this).hasClass("btn-detail");
            var className = "addCourse";
            $comm.modal({
            	"className": className,
            	"tit":isUpdate?"修改课程信息":"课程信息",
            },function(){
            	data.isUpdate = isUpdate;
            	data.startTime = data.startTime.replace(" ","T");
            	data.endTime = data.endTime.replace(" ","T");
            	$addCourseUi.updateCourse({ 
            		"list": data,
            		"dom": $("." + className + " .modal-body"),
            	});
            	isUpdate?$(".addCourse input").removeAttr("disabled"):$(".addCourse input").attr("disabled","disabled");
            	if(data.imgAddress){
            		$("#imgAddress").parent().removeClass("fa fa-plus");
            		$("#imgAddress").parent().css("background-image","url("+data.imgAddress+")");
            		$("#imgAddress").parent().css("background-repeat","no-repeat");
            		$("#imgAddress").parent().css("background-size","auto 100%");
            		$("#imgAddress").parent().css("background-position","center");
            		$("#imgAddress").attr("data-url",data.imgAddress);
            	}
            	$("." + className).modal('show');
            	$("input[type='file']").change(function(){
              	  var params = {
           				files:this.files,
           				obj:this
           			}
           			$upload.minFile(params,function(params){
           				$(params.obj).parent().removeClass("fa fa-plus");
           		   		$(params.obj).parent().css("background-image","url("+params.imgUrl+")");
           		   		$(params.obj).parent().css("background-repeat","no-repeat");
           		   		$(params.obj).parent().css("background-size","auto 100%");
           		   		$(params.obj).parent().css("background-position","center");
           		   		$(params.obj).attr("data-url",params.imgUrl);
           			})
                })
            	$("#updateCourse").unbind("click").bind("click",function(){
              	  	servers.save(data.id);
                })
                var timer =setTimeout(function(){
					$("textarea").txtaAutoHeight();
					clearTimeout(timer);
				},500)
            });
        });
        $("td:last() .btn-delete",row).click(function(){
            var className = "addCourse";
            $comm.modal({
            	"className": className,
            	"tit":"删除课程信息",
            },function(){
            	data.isDelete = true;
            	data.startTime = data.startTime.replace(" ","T");
            	data.endTime = data.endTime.replace(" ","T");
            	$addCourseUi.updateCourse({ 
            		"list": data,
            		"dom": $("." + className + " .modal-body"),
            	});
            	$(".addCourse input").attr("disabled","disabled");
            	if(data.imgAddress){
            		$("#imgAddress").parent().removeClass("fa fa-plus");
            		$("#imgAddress").parent().css("background-image","url("+data.imgAddress+")");
            		$("#imgAddress").parent().css("background-repeat","no-repeat");
            		$("#imgAddress").parent().css("background-size","auto 100%");
            		$("#imgAddress").parent().css("background-position","center");
            		$("#imgAddress").attr("data-url",data.imgAddress);
            	}
            	$("." + className).modal('show');
            	$("#deleteCourse").unbind("click").bind("click",function(){
            		var args = {
            			"id": data.id,
                	}
                	servers.delCourseInfo(args,servers.serchBtn);
            		$("." + className).modal('hide');
                })
                var timer =setTimeout(function(){
					$("textarea").txtaAutoHeight();
					clearTimeout(timer);
				},500)
            });
        });  
        
    };
    /**
     * 初始化完成之后的回调函数
     */
    var initComplete = function(setting,json){
        $("#addCourse").prev("div.row").children().first().removeClass("col-xs-6").addClass("col-xs-12");
        $("#addCourse").prev("div.row").remove();
        $("#resetBtn").click(function(){
            $("##serch-courseDate,#phoneNum,#queue,#hisNo,#timeFrom,#timeTo,#ageFrom-year,#ageFrom-month,#ageTo-year,#ageTo-month").val("");
            $datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
            var args = $datatableUi.table.api().ajax.params();   //获取dt请求参数
        });
        $("#serchBtn").click(servers.serchBtn);
        $("#exportBtn").bind("click",function(){
        	var data = {
                 "lecturerName": $.trim($('#serchLecturerName').val()),
                 "course_name": $.trim($('#serchCourseName').val()),
    			 "startDate":  $.trim($('#serchStartDate').val()),
    			 "endDate":  $.trim($('#serchEndDate').val()),
        	}
        	servers.exportCourseBespeak(data,function(file){
        		console.info(file)
        	});
        })
    }
    servers.serchBtn = function(){
    	 $datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
         var args = $datatableUi.table.api().ajax.params();   //获取dt请求参数 
    }
    
    $.fn.extend({
        txtaAutoHeight: function () {
            return this.each(function () {
                var $this = $(this);
                if (!$this.attr('initAttrH')) {
                    $this.attr('initAttrH', $this.outerHeight());
                }
                setAutoHeight(this).on('input', function () {
                    setAutoHeight(this);
                });
            });
            function setAutoHeight(elem) {
                var $obj = $(elem);
                return $obj.css({ height: $obj.attr('initAttrH'), 'overflow-y': 'hidden' }).height(elem.scrollHeight);
            }
        }
    });
    /*
     * 课程预约-添加课程：
     * */
     servers.addCourse = function(params,callback){
    	 var className = "addCourse";
         $comm.modal({
             "className": className,
             "tit": "添加课程",
         },function(){
        	 $addCourseUi.addCourse({ 
                  "list": [{id:1,reasonName:"3"}],
                  "dom": $("." + className + " .modal-body"),
              });
              $("." + className).modal('show');
              $("input[type='file']").change(function(){
            	  var params = {
         				files:this.files,
         				obj:this
         			}
         			$upload.minFile(params,function(params){
         				$(params.obj).parent().removeClass("fa fa-plus");
         		   		$(params.obj).parent().css("background-image","url("+params.imgUrl+")");
         		   		$(params.obj).parent().css("background-repeat","no-repeat");
         		   		$(params.obj).parent().css("background-size","auto 100%");
         		   		$(params.obj).parent().css("background-position","center");
         		   		$(params.obj).attr("data-url",params.imgUrl);
         			})
              })
              $("#addNoneCourse").unbind("click").bind("click",function(){
            	  servers.save();
              })
         });
     };
     
     servers.save = function(id){
    	 var courseName = $("#courseName").val();
	   	  var lecturerName = $("#lecturerName").val();
	   	  var hospitalName = $("#hospitalName").val();
	   	  var hospitalAddress = $("#hospitalAddress").val();
	   	  var specificAddress = $("#specificAddress").val();
	   	  var startTime = $("#startTime").val();
	   	  var endTime = $("#endTime").val();
	   	  var imgAddress = $("#imgAddress").attr("data-url");
	   	  var courseIntroduce = $("#courseIntroduce").val();
	   	  var upperLimit = $("#upperLimit").val();
	   	  if(!courseName){
	   		  $bb.toastShow("请输入课程名称")
	   	  }else if(lecturerName == ""){
	   		  $bb.toastShow("请输入讲师名称")
	   	  }else if(hospitalName == ""){
	   		  $bb.toastShow("请输入医院名称")
	   	  }else if(hospitalAddress == ""){
	   		  $bb.toastShow("请输入医院地址")
	   	  }else if(startTime == ""){
	   		  $bb.toastShow("请输入课程开始时间")
	   	  }else if(endTime == ""){
	   		  $bb.toastShow("请输入课程结束时间")
	   	  }else if(new Date(startTime).getTime() > new Date(endTime).getTime()){
	   		  $bb.toastShow("课程结束时间小于课程开始时间");
	   	  }else if(upperLimit == ""){
	   		  $bb.toastShow("请输入预约人数上限")
	   	  }else{
	   		imgAddress = imgAddress || "https://bbcare.oss-cn-hangzhou.aliyuncs.com/image/bbcareApp/keyy-banner.png";
	   		  var arg = {
	   				  "id": id||"",
	   				  "courseName": courseName,
	   				  "lecturerName":lecturerName,
	   				  "hospitalName": hospitalName,
	   				  "hospitalAddress": hospitalAddress,
	   				  "specificAddress": specificAddress,
	   				  "courseDate": $bb.simple.getDateFormat(new Date(startTime)).date,
	   				  "startTime": startTime.replace("T"," "),
	   				  "endTime": endTime.replace("T"," "),
	   				  "imgAddress": imgAddress,
	   				  "courseIntroduce": courseIntroduce,
	   				  "upperLimit":upperLimit
	   		  }
	   		  servers.saveCourseInfo(arg,function(data){
	   			   $bb.toastShow(id?"修改成功":"添加成功");
	   			   $(".addCourse").modal('hide');
	   			   servers.serchBtn();
	   		  }); 
	   	  }
     }
     
     /*
      * 课程预约-添加课程：
      * */
      servers.saveCourseInfo = function(params,callback){
          $bb.ajax({
              url: URL + "followup/service/course/saveCourseInfo",
              data: JSON.stringify({
                  data: params
              }),
              success: function (data) {
                  if(data.success){
                      callback(data);
                  }
              }
          });
      };
     
     
     
     
    /*
     * 课程预约-删除课程：
     * */
     servers.delCourseInfo = function(params,callback){
         $bb.ajax({
             url: URL + "followup/service/course/delCourseInfo",
             data: JSON.stringify({
                 data: params
             }),
             success: function (data) {
                 if(data.success){
                     callback(data);
                 }
             }
         });
     };
    /**
     * 获取datatable里的options
     */
    servers.getOptions = function(){
        var sessionId = $bb.getSessionStorage("sessionId");
        var options = {
            "ajax": {
                "url": URL + "followup/service/course/listCourseForPage?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams
            },
            "columns": columnsData(),
            "rowCallback": rowCallback,
            "initComplete": initComplete,
        };
        return options;
    }
    /*
     * 预约数据导出接口：
     * */
    servers.exportCourseBespeak = function(params,callback){
        var sessionId = $bb.getSessionStorage("sessionId");
        window.location.href = URL + "followup/service/course/exportCourseExcel?sessionId=" + sessionId+urlEncode(params);
    };
 // urlEncode
    var urlEncode = function(param, key, encode) {
        if (param==null) return '';
        var paramStr = '';
        var t = typeof (param);
        if (t == 'string' || t == 'number' || t == 'boolean') {
            paramStr += '&' + key + '='  + ((encode==null||encode) ? encodeURIComponent(param) : param); 
        } else {
            for (var i in param) {
                var k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
                paramStr += urlEncode(param[i], k, encode)
            }
        }
        return paramStr;

    }
    return servers;
});